//ajax request holders 
var newItemsAjax, newItemAjax, updatedItemsDetails,searchedItemsAjax;
// const strings
var NEWITEMS = "newItems", SEARCHEDITEMS = "searchedItems";
// holds the item when the view item page is being displayed(otherwise its null)
var selectedItem;
// selected items
var searchedItems = new Array();
// store the newest items
var newItemsArr = [];
// store the publish time of the most new item we are showing
var lastItemPublishTime;

// gets new items from the server
function getNewItems() {
	var url,listener;
	if(isSearchPage()){
		url = insertParam("Search" ,"searchText" ,searchedString); 
		listener = searchListener;
	}else if(isHomePage()){
		url = "NewItems";
		listener = newItemsListener;
	}else{
		syncItemsDetails();
		return;
	}
	url = insertParam(url, "startFrom", lastItemPublishTime);
	newItemsAjax = fire("GET", url, null, listener);
}

// stores the new items in the server as well as it calls the UI updater
function newItemsListener() {
	var fetchedItemsNumber = fetchItemsIntoArray(newItemsArr, newItemsAjax);
	if(fetchedItemsNumber == 0)
		return;
		if (newItemsArr.length > 4)
			newItemsArr.length = 4;
		fetchNewItems(newItemsArr,fetchedItemsNumber);
		lastItemPublishTime = newItemsArr[0].publishTime;	
}

function fetchItemsIntoArray(arr,ajax,updatePublishTime){
	var obj = validResponse(ajax);
	if (obj == undefined || obj.items == undefined){
		return 0;
	}else{
		// since the items are sorted according to publish time we use
		// newItemsArr as stack
		//var i = obj.items.length - 1; i > -1; i--
		for (var i = obj.items.length - 1; i > -1; i--) {
			arr.unshift(obj.items[i]);
			if(updatePublishTime && obj.items[i].publishTime > lastItemPublishTime){
				lastItemPublishTime = obj.items[i].publishTime;
			}
		}
		syncItemsDetails();
		return obj.items.length;
}
}
var newItemsCheckingInterval, updatingItemsInterval;

function startRefreshingItems() {
	// every 5 seconds check for new items
	getNewItems();
	newItemsCheckingInterval = setInterval(getNewItems, 5000);
	// every 5 seconds ask for new details of the items
	// start after checking for new items in 2.5 second to avoid bugs
	//setTimeout(function() {
		//syncItemsDetails();
		//updatingItemsInterval = setInterval(syncItemsDetails, 5000);
	//}, 2500);
}


function stopRefreshingNewItems() {
	clearInterval(newItemsCheckingInterval);
}

function stopRefreshingItems(){
	clearInterval(updatingItemsInterval);
}
// posting a new item
function newItem(params) {
	newItemAjax = fire("POST", "Items", params, postItemListener);
}

function postItemListener() {
	var obj = validResponse(newItemAjax);
	if (obj != undefined) {
		if (obj.result == true) {
			returnToHome();
		} else {
			showError(obj.errorMessage);
		}
	}
}


// sends all the stored items in an array to the server
function syncItemsDetails() {
	var items = new Array();
	if(isHomePage()){
	items = items.concat(newItemsArr);
	}else if (isSearchPage()) {
		items = items.concat(searchedItems);
	}else if (isViewItemPage()) {
		items = items.concat(selectedItem);
	}
	for ( var i = 0; i < items.length; i++) {
		if (items[i] == null || isItemSold(items[i])) {
			items.splice(i--, 1);
		} else
			items[i] = items[i].id;
	}
	if(items.length < 1){
		updateItemsDetails();
		return;
	}
	var url = "Items?itemsToUpdate=" + JSON.stringify(items);
	updatedItemsDetails = fire("GET", url, new Object(),
			syncItemsDetailsListener);
}

// synchronize current
var lastSyncItemIndex;
var syncItems;

function syncItemsDetailsListener() {
	var obj = validResponse(updatedItemsDetails);
	if (obj != undefined && obj.updatedItems.length != null) {
		syncItems = obj.updatedItems;
		lastSyncItemIndex = 0;
			if(isHomePage()){
				copySyncItems(newItemsArr);
			}else if (isSearchPage()) {
				copySyncItems(searchedItems);
			}else if (isViewItemPage()) {
				copySyncItems([ selectedItem ]);
			}
		updateItemsDetails();
	}
}

function copySyncItems(items) {
	if (items != null) {
		for ( var i = 0; i < items.length; i++) {
			if (items[i] == null || isItemSold(items[i])) {
				continue;
			}
			items[i].currentBidAmount = syncItems[lastSyncItemIndex].currentBidAmount;
			items[i].winnerUserName = syncItems[lastSyncItemIndex].winnerUserName;
			lastSyncItemIndex++;
		}
	}
}

function getCachedNewItems() {
	return newItemsArr;
}

// except new item arr
function emptyCachedItems() {
	selectedItem = null;
	searchedItems.length = 0;
}


var lastSearchedItemPublishTime;
var searchedString;

//search items
function searchForItems(string){
	searchedString = string;
	lastItemPublishTime = null;
	getNewItems();
}


function searchListener(){
	if(fetchItemsIntoArray(searchedItems,this,true) == 0)
		return;
	fetchSearchedItems(searchedItems);
}

function restoreHomelastItemPublishTime(){
	lastItemPublishTime = newItemsArr[0].publishTime;
}

function isItemSold(item){
	return item.sellTime < new Date().getTime();
}

	setTimeout(function() {
	startRefreshingItems();
	},15);